package cn.mg.framework.response;

import cn.mg.framework.annotations.ResponseResult;
import cn.mg.framework.util.json.JsonUtil;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author hezhaoming
 * @date 2019-11-05
 */
@ControllerAdvice
public class ResponseResultAdvice implements ResponseBodyAdvice {


    public static final String RESPONSE_RESULT = "RESPONSE-RESULT";

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        ResponseResult requestAttribute = (ResponseResult) request.getAttribute(RESPONSE_RESULT);
        return requestAttribute != null;
    }


    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass,
                                  ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        ResponseResult responseResultAnn = (ResponseResult) request.getAttribute(ResponseResultInterceptor.RESPONSE_RESULT);

        Class<? extends Result> resultClazz = responseResultAnn.value();

        if (resultClazz.isAssignableFrom(PlatformResult.class)) {
            if (body instanceof PlatformErrorResult) {
                PlatformErrorResult platformErrorResult = (PlatformErrorResult) body;
                return PlatformResult.builder()
                        .code(platformErrorResult.getCode())
                        .message(platformErrorResult.getMessage())
                        .data(platformErrorResult.getErrors())
                        .build();
            } else if (body instanceof String) {
                return JsonUtil.obj2json(PlatformResult.success(body));
            }
            return PlatformResult.success(body);
        }
        return body;
    }
}

